<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
          >
            <template v-slot:form-deptName>
              <el-input
                v-model="formInfo.data.deptName"
                class="not-mongolia"
                type="input"
                placeholder="请选择部门"
                :disabled="true"
              >
                <template #append>
                  <el-icon @click="_selectDept"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-managerUserName>
              <el-input
                v-model="formInfo.data.managerUserName"
                class="not-mongolia"
                type="input"
                placeholder="请选择管理员"
                :disabled="true"
              >
                <template #append>
                  <el-icon @click="selectUserName"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-warningNoticeUserName>
              <el-input
                v-model="formInfo.data.warningNoticeUserName"
                class="not-mongolia"
                type="input"
                placeholder="请选择预警通知人"
                :disabled="true"
              >
                <template #append>
                  <el-icon @click="selectUserNameList"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
    </NewFullScreen>
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :query="selectDeptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectDeptCallback"
    />
    <select-no-auth-users
      v-if="userInfo.visible"
      v-model:showDialog="userInfo.visible"
      :query="userInfo.query"
      :api="userInfo.api"
      :checkedList="userInfo.expandedKeys"
      :checkBox="selectTreesMultiple"
      :highlight-row="true"
      :save-empty="true"
      @callback="callBackUsers"
    />
  </div>
</template>

<script setup name="DepotModify">
import PageForm from '@/components/PageForm/index'
import SelectNoAuthUsers from '@/components/SelectUsers/selectNoAuthUsers'
import selectDept from '@/components/SelectDept/index'
import { getRrgUserList } from '@/api/base.js'
import {
  createDepot,
  updateDepot,
  getDepotAll,
  getDepotById,
} from '@/api/core.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  id: {},
})

const selectTreesMultiple = ref(false)
const listTypeInfo = reactive({
  depotList: [],
})
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const formInfo = reactive({
  ref: null,
  data: {
    deptName: '',
    deptId: '',
    managerUserName: '',
    managerUserId: '',
    warningNoticeUserName: '',
    warningNoticeUser: '',
  },
  fieldList: [
    { label: '仓库名称', value: 'name', type: 'input', required: true },
    { label: '仓库编码', value: 'code', type: 'input', required: true },
    {
      label: '仓库类型',
      value: 'type',
      type: 'select-model',
      required: true,
      code: 'depot_type',
    },
    {
      label: '仓库状态',
      value: 'status',
      type: 'radio-model',
      required: true,
      code: 'enabled_type',
      disabled: !!props.id,
    },
    {
      label: '可领仓库',
      value: 'supDepotIds',
      type: 'select',
      list: 'depotList',
      collapseTags: true,
      multiple: true,
      filterable: true,
    },
    { label: '所属部门', value: 'deptName', type: 'slot' },
    { label: '仓库管理员', value: 'managerUserName', type: 'slot' },
    { label: '预警通知人', value: 'warningNoticeUserName', type: 'slot' },
    {
      label: '验证上次批号',
      value: 'validateBatchNumber',
      labelTip: '消耗登记对比两次批号是否一致',
      type: 'select-model',
      code: 'yes_or_no',
    },
    {
      label: '默认使用子盘点',
      value: 'defaultUseSub',
      type: 'select-model',
      checkDefault: true,
      code: 'use_sub',
    },
    {
      label: '是否允许有库存冻结时盘点',
      value: 'allowFrozenInventory',
      type: 'select-model',
      code: 'yes_or_no',
    },
    {
      label: '用途类型',
      value: 'useTypeId',
      multiple: true,
      type: 'select-model',
      code: 'depot_use_type',
      checkDefault: false,
    },
    {
      label: '是否货位管理',
      value: 'isCargoSpaceManage',
      type: 'select-model',
      checkDefault: true,
      code: 'is_cargo_space_manage',
      disabled: false,
    },
    {
      label: '是否仓库以领定消',
      value: 'isReceiveConsume',
      type: 'select-model',
      code: 'yes_or_no',
      show: !props.id,
      clearable: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
    code: [
      { required: true, message: '请输入仓库编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    type: [{ required: true, message: '请选择仓库类型', trigger: 'blur' }],
    status: [{ required: true, message: '请选择仓库状态', trigger: 'blur' }],
    deptName: [
      { required: true, message: '请选择所属部门', trigger: 'change' },
    ],
    // managerUserName: [
    //   { required: true, message: "请选择仓库管理员", trigger: "change" }
    // ],
    // warningNoticeUserName: [
    //   { required: true, message: "请选择预警通知人", trigger: "change" }
    // ],
    useTypeId: [
      { required: true, message: '请选择用途类型', trigger: 'change' },
    ],
  },
  labelWidth: '140px',
})
const selectDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const userInfo = reactive({
  expandedKeys: [],
  visible: false,
  api: getRrgUserList,
  query: {
    statusMult: 1,
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    // 更新父组件visible
    emit('update:visible', newValue)
  },
})

watch(
  () => formInfo.data.status,
  (value) => {
    if (value === 1 && !props.id) {
      formInfo.fieldList[11].disabled = false
      setTimeout(() => {
        isDisIsReceiveConsume(false)
      }, 0)
    } else {
      formInfo.fieldList[11].disabled = true
      formInfo.data.isCargoSpaceManage = formInfo.data.isCargoSpaceManage
        ? formInfo.data.isCargoSpaceManage
        : 0
      formInfo.data.isCargoSpaceManageValue = formInfo.data
        .isCargoSpaceManageValue
        ? formInfo.data.isCargoSpaceManageValue
        : '否'
      setTimeout(() => {
        formInfo.data.isReceiveConsume = ''
        isDisIsReceiveConsume(true)
      }, 0)
    }
  },
  {
    immediate: true,
  }
)

onMounted(() => {
  getDepotList()
  if (props.id) {
    getEdit()
  }
})

function isDisIsReceiveConsume(type) {
  formInfo.fieldList.forEach((element) => {
    if (element.value === 'isReceiveConsume') {
      element.disabled = type
    }
  })
}

//保存
function save() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let api = props.id ? updateDepot : createDepot
      const params = formInfo.data
      api(params).then((res) => {
        if (res.success) {
          showDialog.value = false
          emit('returnModify', false)
        }
      })
    }
  })
}
function getDepotList(params = {}) {
  params.idNotIn = props.id
  params.status = '1'
  listTypeInfo.depotList = []
  getDepotAll(params).then((resp) => {
    if (resp && resp.success) {
      const data = resp.data
      for (let item of data) {
        listTypeInfo.depotList.push({
          key: item.name,
          value: item.id,
        })
      }
    }
  })
}
function getEdit() {
  getDepotById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
    }
  })
}
//选择部门
function _selectDept() {
  selectDeptInfo.visible = true
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data.deptId = row.id
    formInfo.data['deptName'] = row.name
  } else {
    formInfo.data.deptId = ''
    formInfo.data['deptName'] = ''
  }
}
//选择人员
function selectUserName() {
  userInfo.visible = true
  selectTreesMultiple.value = false
  userInfo.expandedKeys = []
}
//选择人员
function selectUserNameList() {
  userInfo.visible = true
  selectTreesMultiple.value = true
  userInfo.expandedKeys = []
  let warningNoticeUser = formInfo.data.warningNoticeUser
  if (warningNoticeUser) {
    let users = warningNoticeUser.split(',')
    users.forEach((val) => userInfo.expandedKeys.push(Number(val)))
  }
}
function callBackUsers(row) {
  if (row) {
    if (!selectTreesMultiple.value) {
      formInfo.data.managerUserId = row.id
      formInfo.data['managerUserName'] = row.name
    } else {
      formInfo.data.warningNoticeUser = row.map((val) => val.id).join(',')
      formInfo.data['warningNoticeUserName'] = row
        .map((val) => val.name)
        .join(',')
    }
  } else {
    if (!selectTreesMultiple.value) {
      formInfo.data.managerUserId = null
      formInfo.data['managerUserName'] = ''
    } else {
      formInfo.data.warningNoticeUser = ''
      formInfo.data['warningNoticeUserName'] = ''
    }
  }
}
</script>
